package work.vcloud.baseinfo.utils;

import java.io.ByteArrayInputStream;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;

@Component
public class OssUtil {
	private static String accessKey;
    private static String secretKey;
    private static String endpoint;
    private static String bucketName;
    private static String realmPath;

    @Value("${web.accessKey}")
    public void setAccessKey(String accessKey) {
    	OssUtil.accessKey = accessKey;
    }
    
    @Value("${web.secretKey}")
	public void setSecretKey(String secretKey) {
    	OssUtil.secretKey = secretKey;
	}

    @Value("${web.endpoint}")
	public void setEndpoint(String endpoint) {
    	OssUtil.endpoint = endpoint;
	}

    @Value("${web.bucket_name}")
	public void setBucketName(String bucketName) {
    	OssUtil.bucketName = bucketName;
	}
	
    @Value("${web.realmPath}")
    public void setRealmPath(String realmPath) {
    	OssUtil.realmPath = realmPath;
    }
    
	public static String upload(byte[] buffer, String filePath) {
		try {
			AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
			ClientConfiguration clientConfig = new ClientConfiguration();
			clientConfig.setProtocol(Protocol.HTTP);
		
			AmazonS3 s3 = new AmazonS3Client(credentials, clientConfig);
			s3.setEndpoint(endpoint);
			
			// ceph用到
//			s3.setS3ClientOptions(S3ClientOptions.builder().setPathStyleAccess(true).build());
		
			// 列出桶下面的清单
//			ObjectListing objects = s3.listObjects(bucket_name);
//			do {
//				for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
//					System.out.println(objectSummary.getKey() + "\t" + objectSummary.getSize() + "\t"
//							+ StringUtils.fromDate(objectSummary.getLastModified()));
//				}
//				objects = s3.listNextBatchOfObjects(objects);
//			} while (objects.isTruncated());
		
			// 上传
			ByteArrayInputStream input = new ByteArrayInputStream(buffer);
			s3.putObject(bucketName, filePath, input, new ObjectMetadata());
			
			return realmPath + filePath;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return e.getMessage();
		}
	}
}
